<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" size="mini">
      <el-query-row :label="'筛选项'">
        <el-col :span="4" class="mb10">
          <el-form-item prop="projectId">
            <el-select
              v-model="queryParams.projectId"
              placeholder="品类"
              style="width: 100%;"
              filterable
              @change="_projectChange"
            >
              <el-option
                v-for="(item, index) in projectList"
                :key="item + index"
                :label="item.projectName"
                :value="item.pid"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="mb10">
          <el-form-item prop="productId">
            <el-select
              v-model="queryParams.productId"
              placeholder="产品"
              style="width: 100%;"
              multiple
              collapse-tags
              filterable
              @change="_productChange"
            >
              <el-option
                v-for="(item, index) in productList"
                :key="item + index"
                :label="item.name"
                :value="item.pid"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="mb10">
          <el-form-item prop="author_status">
            <el-select
              v-model="queryParams.author_status"
              placeholder="授权状态"
              style="width: 100%;"
              filterable
            >
              <el-option
                v-for="(item, index) in authorStatusList"
                :key="item + index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="mb10">
          <el-form-item prop="source">
            <el-select
              v-model="queryParams.source"
              placeholder="来源"
              style="width: 100%;"
              filterable
            >
              <el-option
                v-for="(item, index) in sourceList"
                :key="item + index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="mb10">
          <el-form-item prop="user_id">
            <el-select
              v-model="queryParams.user_id"
              placeholder="人员"
              style="width: 100%;"
              multiple
              collapse-tags
              filterable
            >
              <el-option
                v-for="(item, index) in userList"
                :key="item + index"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="mb10">
          <el-form-item prop="account_id">
            <el-input
              v-model="queryParams.account_id"
              placeholder="账号ID"
              style="width: 100%;"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4" class="mb10">
          <el-form-item prop="account_name">
            <el-input
              v-model="queryParams.account_name"
              placeholder="广告投放账号"
              style="width: 100%;"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4" class="mb10">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-query-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="_batchBindBtnHandler(3)"
        >批量绑定人员</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="_batchBindBtnHandler(4)"
        >批量绑定产品</el-button>
      </el-col>
    </el-row>
    
    <el-table v-loading="loading" :data="accountList" :height="tableHeight" :key="queryParams + tableHeight" :default-sort="defaultSort" @sort-change="_changeSort" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="同步状态" align="center" prop="status">
        <template #default="scope">
          <span>{{scope.row['status'] ? '开启' : '关闭'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="账号ID" align="center" prop="account_id" />
      <el-table-column label="广告投放账号" align="center" prop="account_name" />
      <el-table-column label="账号别名" align="center" prop="alias">
        <template #default="scope">
          <span v-if="scope.row['alias']">
            {{scope.row['alias']}}
            <i class="el-icon-edit ml5" @click="_columnEdit(scope.row, scope.$index, 1)" style="cursor:pointer;"></i>
          </span>
          <span v-else style="color:blue;cursor:pointer;" @click="_columnEdit(scope.row, scope.$index, 1)">添加</span>
        </template>
      </el-table-column>
      <el-table-column label="授权状态" align="center" prop="author_status">
        <template #default="scope">
          <span>{{authorStatusConfig[scope.row['author_status']]}}</span>
        </template>
      </el-table-column>
      <el-table-column label="活跃状态" align="center" prop="account_status">
        <template #default="scope">
          <span>{{scope.row['account_status'] ? '活跃' : '停用'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="品类/产品" align="center" prop="product_name">
        <template #default="scope">
          <span>{{scope.row['project_name']}}/{{scope.row['product_name']}}</span>
        </template>
      </el-table-column>
      <el-table-column label="人员" align="center" prop="user_name">
        <template #default="scope">
          <span v-if="scope.row['user_name']">
            {{scope.row['user_name']}}
            <i class="el-icon-edit ml5" @click="_columnEdit(scope.row, scope.$index, 2)" style="cursor:pointer;"></i>
          </span>
          <span v-else style="color:blue;cursor:pointer;" @click="_columnEdit(scope.row, scope.$index, 2)">添加</span>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="source" />
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="批量绑定人员" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="50px">
        <el-form-item label="别名" prop="alias" v-if="form.type == 1">
          <el-input v-model="form.alias" placeholder="请填写别名" />
        </el-form-item>
        <el-form-item label="人员" prop="user_id" v-if="[2, 3].includes(form.type)">
          <el-select
              v-model="form.user_id"
              placeholder="请选择人员"
              style="width: 100%;"
              filterable
            >
              <el-option
                v-for="(item, index) in userList"
                :key="item + index"
                :label="item.nickName"
                :value="item.userId"
              />
            </el-select>
        </el-form-item>
        <el-form-item prop="projectId" v-if="form.type == 4">
          <el-select
            v-model="form.projectId"
            placeholder="品类"
            style="width: 100%;"
            filterable
            @change="_projectChange"
          >
            <el-option
              v-for="(item, index) in projectList"
              :key="item + index"
              :label="item.projectName"
              :value="item.pid"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="productId" v-if="form.type == 4">
          <el-select
            v-model="form.productId"
            placeholder="产品"
            style="width: 100%;"
            filterable
            @change="_productChange"
          >
            <el-option
              v-for="(item, index) in productList"
              :key="item + index"
              :label="item.name"
              :value="item.pid"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import baseTableAdv from '@/mixins/baseTableAdv';
import { arrParamToStr } from '@/utils/index';
import { listAccount, updateAlias, updateUser, batchBindUser, batchBindProduct } from "@/api/system/account";
export default {
  name: 'Account',
  mixins: [baseTableAdv],
  data () {
    return {
      // 默认排序
      defaultSort: {prop: 'createTime', order: 'descending'},
      // 表头数据
      theadList: [
        {name: '同步状态', value: 'status'},
        {name: '账号ID', value: 'account_id'},
        {name: '广告投放账号', value: 'account_name'},
        {name: '账号别名', value: 'alias'},
        {name: '授权状态', value: 'author_status'},
        {name: '活跃状态', value: 'account_status'},
        {name: '品类/产品', value: 'product_name'},
        {name: '人员', value: 'user_name'},
        {name: '来源', value: 'source_name'},
      ],
      // 表格数据
      accountList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectname: [],
        productname: [],
        source: '',
        author_status: '',
        user_id: '',
        account_name: ''
      },
      // 授权状态
      authorStatusConfig: {
        1: '成功',
        2: '失败',
        3: '不可用'
      },
      authorStatusList: [
        {name: '成功', value: 1},
        {name: '失败', value: 2},
        {name: '不可用', value: 3},
      ],
      // 来源
      sourceList: [
        {name: '账号管家', value: 1},
        {name: '广告主', value: 2},
        {name: '代理商', value: 3},
      ],
      // 项目数据
      projectList: [],
      // 产品数据
      productList: [],
      // 人员
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        user_id: '',
        projectId: '',
        productId: ''
      },
      // 表单校验
      rules: {
        alias: [
          { required: true, message: "请选填写别名", trigger: "blur" }
        ],
        user_id: [
          { required: true, message: "请选择人员", trigger: "change" }
        ]
      },
      currRowIndex: null
    }
  },
  created() {
    this.getList();
    this._getProjectList();
    this._getUserList();
  },
  methods: {
    // 更新账号别名
    _updateAlias (row) {
      updateAlias({account_id: row.account_id, alias: row.alias, source: row.source}).then(response => {
        if (response.code === 200) {
          this.getList();
          this.open = false;
          this.$modal.msgSuccess("操作成功！");
        } else {
          this.$modal.msgError("操作失败！");
        }
      });
    },
    // 更新人员
    _updateUser (row) {
      updateUser({account_id: row.account_id, pid: row.pid, user_id: row.user_id, source: row.source}).then(response => {
        if (response.code === 200) {
          this.getList();
          this.open = false;
          this.$modal.msgSuccess("操作成功！");
        } else {
          this.$modal.msgError("操作失败！");
        }
      });
    },
    // 批量绑定人员
    _batchBindUser () {
      batchBindUser({pid: this.form.pid, accountId: this.form.account_id, user_id: this.form.user_id, source: this.form.source}).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.open = false;
        this.getList();
      });
    },
    // 批量绑定产品
    _batchBindProduct () {
      batchBindProduct({accountId: this.form.account_id, productId: this.form.productId, source: this.form.source}).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.open = false;
        this.getList();
      });
    },
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.type == 1) this._updateAlias(this.form)
          if (this.form.type == 2) this._updateUser(this.form)
          if (this.form.type == 3) this._batchBindUser(this.form)
          if (this.form.type == 4) this._batchBindProduct(this.form)
        }
      });
    },
    _columnEdit (row, index, value) {
      this.form = {
        type: value,
        account_id: row.account_id,
        pid: row.pid,
        alias: row.alias,
        user_id: row.user_id
      };
      this.open = true;
    },
    /** 查询ROI数据列表 */
    getList() {
      let vm = this;
      vm.loading = true;
      listAccount(arrParamToStr({...vm.queryParams})).then(response => {
        vm.accountList = response.rows.map(item => {
          let { user_id } = item;
          item.user_id = Number(user_id)
          item.isEdit = false;
          return item;
        });
        vm.total = response.total;
        vm.loading = false;
      }).catch(error => {
        vm.loading = false;
        console.log(error);
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.single = selection.length!==1;
      this.multiple = !selection.length;
      this.form.pid = selection.map(item => item.pid).join(',');
      this.form.account_id = selection.map(item => item.account_id).join(',');
      this.form.source = selection.map(item => item.source).join(',');
    },
    _batchBindBtnHandler (type) {
      this.form.type = type;
      this.form.user_id = '';
      this.form.projectId = '';
      this.form.productId = '';
      this.open = true;
    }
  }
}
</script>